<!--
  @Description:个人中心配置
  @Author:zqy
  @Date:2023-08-17 15:50:24
  @Last Modified by:zqy
  @Last Modified time:2023-08-17 15:50:24
-->
<template>
  <div>
    <table-box
      ref="refTable"
      :selected-arry.sync="tableSelected"
      :table-config="tableConfig"
      :other-filters="otherFilters"
      :off-set="-10"
      table-row-key="id"
      show-index
      :table-sortale="false"
      :show-custom-collect="false"
      :show-custom-combine="false"
      :show-custom-setting="false"
      :setting-auto-request="false"
      @btnOperate="btnOperate"
    />
    <GroupMgt
      v-if="showGroupMgt"
      ref="refGroup"
      :visible.sync="showGroupMgt"
    />
    <Edit
      v-if="showEdit"
      ref="refEdit"
      :visible.sync="showEdit"
      :detail="activeRowData"
      @success="refreshTable"
    />
  </div>
</template>

<script>
import { parseTime } from '@/utils'
import { queryBtnList } from '@/api/permissions'
import { delConfig, updateSort } from '@/api/personCenterConf'
import GroupMgt from './GroupMgt'
import Edit from './Edit'
export default {
  name: 'PersonalCenterConfig',
  components: {
    GroupMgt,
    Edit
  },
  data() {
    const that = this
    return {
      showGroupMgt: false, // 分组管理编辑控制
      showEdit: false, // 是否编辑基础信息
      activeRowData: '', // 当前选中行数据
      tableSelected: [], // 当前所选中表格行数据
      otherFilters: [], // 表格额外查询条件
      tableConfig: {
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/personalCenterEntry/page`,
        onlySearchBar: false,
        pageSize: 20,
        sort: '',
        order: 'asc',
        setting: [
          {
            prop: 'iconPicUrl',
            label: '入口图标',
            minWidth: 100,
            overflowHidden: false,
            sortable: false,
            type: 'hidden',
            align: 'center',
            render: (_h, row) => {
              const iconUrl = row.iconPicUrl || ''
              if (iconUrl) {
                const url = that.formatImageUrl(iconUrl)
                return (<div class='cate_img'><img src={url} /></div>)
              }
              return ''
            }
          },
          {
            prop: 'name',
            label: '入口名称',
            minWidth: 150
          },
          {
            prop: 'groupName',
            label: '分组',
            minWidth: 250
          },
          {
            prop: 'sort',
            label: '排序',
            minWidth: 200,
            sortable: false,
            type: 'hidden',
            overflowHidden: false,
            render: (_h, row) => {
              const btns = []
              if (this.hasPermission('top')) {
                btns.push(<el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 'top')} class='btn-green my-txt-btn'>置顶</el-button>)
              }
              if (this.hasPermission('up')) {
                btns.push(<el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 'moveUp')} class='btn-green my-txt-btn'>上移</el-button>)
              }
              if (this.hasPermission('down')) {
                btns.push(<el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 'moveDown')} class='btn-green my-txt-btn'>下移</el-button>)
              }
              if (this.hasPermission('bottom')) {
                btns.push(<el-button type='text' size='mini' onClick={that.handleSort.bind(this, row, 'bottom')} class='btn-green my-txt-btn'>置底</el-button>)
              }
              return _h('div', btns)
            }
          },
          {
            prop: 'createBy',
            label: '创建人',
            minWidth: 150,
            type: 'hidden'
          },
          {
            prop: 'createTime',
            label: '创建时间',
            minWidth: 150,
            type: 'hidden',
            formatData: ({ createTime }) => {
              return parseTime(createTime)
            }
          },
          {
            prop: 'lastUpdateBy',
            label: '修改人',
            minWidth: 150,
            type: 'hidden'
          },
          {
            prop: 'lastUpdateTime',
            label: '修改时间',
            minWidth: 150,
            type: 'hidden',
            formatData: ({ lastUpdateTime }) => {
              return parseTime(lastUpdateTime)
            }
          }],
        btnList: !this.isProduction ? [
          {
            buttonName: '分组管理',
            optCode: 'group',
            outerFlag: true
          },
          {
            buttonName: '新增',
            optCode: 'add',
            outerFlag: true
          },
          {
            buttonName: '编辑',
            optCode: 'edit',
            outerFlag: true
          },
          {
            buttonName: '删除',
            optCode: 'del',
            outerFlag: true
          }] : null,
        sortersRow: [
          { id: 'groupSort', property: 'groupSort', direction: 'asc' },
          { id: 'sort', property: 'sort', direction: 'asc' }
        ]
      },
      buttons: [],
      sorting: false
    }
  },

  created() {
    this.getBtnsList()
  },
  methods: {
    getBtnsList() {
      const menuCode = this.$route.query.menuCode
      if (!menuCode) return
      const buttonGroupCode = 'inRow'
      queryBtnList({ menuCode, buttonGroupCode }).then(res => {
        // res.data.groovyList
        this.buttons = (res.data && res.data.groovyList) || []
      })
    },
    hasPermission(code) {
      if (!this.isProduction) return true
      return this.buttons.filter(v => v.buttonCode === code).length > 0
    },
    btnOperate(code) {
      switch (code) {
        case 'group':
          this.showGroupMgt = true
          break
        case 'add':
          this.handleEdit()
          break
        case 'edit':
          if (!this.singleJudge(this.tableSelected, '编辑', true)) {
            return
          }
          this.handleEdit(this.tableSelected[0])
          break
        case 'del':
          if (!this.singleJudge(this.tableSelected, '删除', true)) {
            return
          }
          this.handleDelete()
          break
        case 'disable':
          if (!this.singleJudge(this.tableSelected, '停用', true)) {
            return
          }
          this.handleChangeStatus(0) // state 1：启用  0：停用
          break
        case 'enable':
          if (!this.singleJudge(this.tableSelected, '启用', true)) {
            return
          }
          this.handleChangeStatus(1) // state 1：启用  0：停用
          break
        default:
          break
      }
    },
    // 刷新表格数据
    refreshTable(isInit) {
      this.$nextTick(() => {
        this.$refs.refTable.initTableData(isInit ? '' : 'onPage')
      })
    },
    // 新增/编辑基础信息
    handleEdit(row) {
      this.activeRowData = row && row.id ? row : ''
      this.$nextTick(() => {
        this.showEdit = true
      })
    },
    // 删除处理
    handleDelete() {
      const { id, name } = this.tableSelected[0]
      this.$confirm(`此操作将永久删除入口：${name}, 是否继续?`, '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delConfig(id).then(res => {
          if (res.success === 1) {
            this.$message({
              message: res.msg || '删除成功',
              type: 'success'
            })
            this.refreshTable()
          }
        })
      }).catch(() => {})
    },
    /**
     * 排序
     * @param {Object} row 排序行
     * @param {string} type 移动类型：bottom 置底 ，top 置顶 ， moveDown 下移 ，  moveUp 上移
    */
    handleSort(row, type) {
      if (this.sorting) return
      const now = Date.now()
      if (this.sortTime) {
        const diffTime = Math.floor((now - this.sortTime) / 1000)
        // 对比排序操作时间差，大于2s的可操作
        if (diffTime < 2) return
      }
      this.sortTime = now
      const params = {
        id: row.id,
        type
      }
      this.sorting = true
      updateSort(params).then(res => {
        this.sorting = false
        if (res.success === 1) {
          this.refreshTable()
        }
      }).catch(() => {
        this.sorting = false
      })
    }
  }
}
</script>
<style lang='scss' scoped>
  .my-txt-btn{
    padding: 0 !important;
  }
 .cate_img{
    padding: 5px 0;
    line-height: 0;
    font-size: 0;
    img{
      width: 35px;
      height: 35px;
      // object-fit: cover;
      object-fit: contain;
    }
  }
</style>
